import os
import pymongo
import configparser
import common.gyblog as log
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service as ChromeService

LOG = log.get_logger()
SERVICE = ChromeService(executable_path="../common/chromedriver.exe")
CONNECTION_STR = 'mongodb://192.168.0.196:27017/?readPreference=primary&appname=MongoDB%20Compass%20Community&ssl=false'

# 读取配置
cf = configparser.ConfigParser()
cf.read(os.path.dirname(os.path.abspath('.')) + '/download_javbook/config.ini')
DATA_BASE = cf.get('javbook', 'DATA_BASE')
DB_COL = cf.get('javbook', 'DB_COL')
SERIES = cf.get('javbook', 'SERIES')
YEAR = cf.get('javbook', 'YEAR')

'''
抓取tor优先级：
[ThZu.Cc] > [Thz.la]
1080p > 720p
'''


def seek_tor_by_year(year):
    # 连接数据库
    db_client = pymongo.MongoClient(CONNECTION_STR)
    db_database = db_client[DATA_BASE]
    db_col = db_database[DB_COL]
    # 查询
    query = {'series': SERIES, 'year': year}
    projection = {'_id': 0, 'detail_url': 1, 'tor': 1}
    query_ans = list(db_col.find(query, projection))
    # 关闭数据库连接
    db_client.close()
    # 结果处理
    ans = []
    if len(query_ans) != 0:
        for q in query_ans:
            if q['tor'] == '':
                ans.append(q['detail_url'])
    else:
        print('没有搜到：{}'.format(year))
        LOG.info('没有搜到：{}'.format(year))
    return ans


def save_tor(url):
    try:
        # 创建 WebDriver 对象
        driver = webdriver.Chrome(service=SERVICE)
        driver.get(url)
        elements = driver.find_elements(By.XPATH, '/html/body/div[7]/div[position()]/span/a')

        # 连接数据库
        db_client = pymongo.MongoClient(CONNECTION_STR)
        db_database = db_client[DATA_BASE]
        db_col = db_database[DB_COL]

        # 遍历元素并获取 href 属性
        ans = []
        for element in elements:
            name = element.text
            ratio = element.text.split('-')[-1]
            if '[ThZu.Cc]' in name and ratio == '1080p':
                tor = element.get_attribute('href')
                ans.append([name, tor])
        for element in elements:
            name = element.text
            ratio = element.text.split('-')[-1]
            if '[psk.la]' in name and ratio == 'FHD':
                tor = element.get_attribute('href')
                ans.append([name, tor])
        for element in elements:
            name = element.text
            ratio = element.text.split('-')[-1]
            if ratio == 'FHD':
                tor = element.get_attribute('href')
                ans.append([name, tor])

            # if '3xplanet' in name:
            #     tor = element.get_attribute('href')
            #     ans.append(tor)
            # if '[UNCENSORED]' in name:
            #     tor = element.get_attribute('href')
            #     ans.append(tor)
            # if '[JAV][Uncensored]' in name and '[1080p]' in name:
            #     tor = element.get_attribute('href')
            #     ans.append(tor)
            # if '会飞的象' in name:
            #     tor = element.get_attribute('href')
            #     ans.append(tor)
        if len(ans) == 0:
            print('{}：没有找到tor'.format(url))
            LOG.info('{}：没有找到tor'.format(url))
        else:
            query = {'detail_url': url}
            new_values = {"$set": {"tor": ans[0][1], "tor_name": ans[0][0]}}
            db_col.update_one(query, new_values)
            print('已插入:{},{},{}'.format(ans[0][1], ans[0][0], url))
            LOG.info('已插入:{},{},{}'.format(ans[0][1], ans[0][0], url))
        driver.close()
        db_client.close()
    except:
        print(url, 'error')


def query_tor_by_year(year):
    # 连接数据库
    db_client = pymongo.MongoClient(CONNECTION_STR)
    db_database = db_client[DATA_BASE]
    db_col = db_database[DB_COL]

    ans = []
    error_ans = []

    # 查询
    query = {'series': SERIES, 'year': year}
    projection = {'_id': 0, 'tor': 1, 'num': 1}
    query_ans = list(db_col.find(query, projection))
    for q in query_ans:
        if q['tor'] == '':
            error_ans.append(q['num'])
        else:
            ans.append(q['tor'])
    print('搜索到的磁力：')
    for a in ans:
        if a != '':
            print(a)
    print('未搜索到的番号：')
    for e in error_ans:
        print(e)
    print('共{}个，{}有tor,{}没有'.format(len(query_ans), len(ans), len(error_ans)))
    db_client.close()


if __name__ == '__main__':
    ans = seek_tor_by_year(YEAR)
    print('根据条件{}年，共搜索到{}个视频'.format(YEAR, len(ans)))

    for a, url in enumerate(ans):
        save_tor(url)
        print('进度：{}/{}'.format(str(a + 1), len(ans)))

    query_tor_by_year(YEAR)
